const app = getApp()

Page({
  data: {
    nowtap: 1,
    article: null,
    is_art_collect:false,
    //
    imgPage: 1,
    imgNumber: [],
    imglist: [],
    //
    videoPage: 1,
    videoList: [],
    preVideoId: 0,
    preVideoIndex: 0,
    vStorage:[],
    //
    showList: [],
    show: true,
    //
    nowMusic: [],
    nowMusicId: 0,
    musicIdList: [],
    is_play: false,
    is_animation: false,

    is_first_play: true,
    first_audio_url: '',
    audioContext: null,

    musicX: 0,
    musicY: 0,
    //
    musicflag: false,
    videoflag: false,
  },

  onLoad: function() {
    var that = this
    // 获取显示控制配置
    wx.request({
      url: app.globalData.url + 'medias/config?v=' + app.globalData.version,
      success: (res) => {
        that.setData({
          musicflag: res.data.data.musicflag,
          videoflag: res.data.data.videoflag
        })
      }
    });
    // 获取音乐
    that.getMusic()

    // 判断是否从文章分享进入
    var artId = wx.getStorageSync('artId')
    if (artId) {
      wx.request({
        url: app.globalData.url + 'articles/today?id=' + artId,
        success: (res) => {
          // console.log(res);
          that.setData({
            article: res.data.data,
            nowtap: 0
          })
          wx.setNavigationBarTitle({
            title: '每日一文'
          });
        },
        fail: () => {}
      });
    } else {
      that.getDayArticle()
      that.getImgList()
    }
  },

  onShow: function() {
    var that = this
    var artId = wx.getStorageSync('artId')
    if (artId) {
      wx.request({
        url: app.globalData.url + 'articles/today?id=' + artId,
        success: (res) => {
          // console.log(res);
          that.setData({
            article: res.data.data,
            nowtap: 0
          })
          wx.setNavigationBarTitle({
            title: '每日一文'
          });
          wx.removeStorageSync('artId')
        },
        fail: () => {}
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    console.log(e);
    if (e.target) {
      if (e.target.dataset.type == "shareAeticle") {
        var id = e.target.dataset.id
        var title = e.target.dataset.title
        return {
          title: title,
          imageUrl: imageUrl,
          path: '/pages/detail/detail?type=shareArticle&id=' + id
        }
      } else if (e.target.dataset.type == 'shareVideo') {
        var id = e.target.dataset.id
        var title = e.target.dataset.title
        var imageUrl = e.target.dataset.imageUrl
        return {
          title: title,
          imageUrl: imageUrl,
          path: '/pages/detail/detail?type=shareVideo&id=' + id
        }
      }
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this
    if (that.data.nowtap == 1) {
      that.getImgList(that.data.imgPage)
    } else if (that.data.nowtap == 2) {
      that.getVideoList(that.data.videoPage)
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var that = this

    if (that.data.nowtap == 0) {
      wx.request({
        url: app.globalData.url + 'articles/random',
        method: 'POST',
        success: (res) => {
          // console.log(res);
          that.setData({
            article: res.data.data
          })
        },
        fail: () => {},
        complate: function() {
          wx.stopPullDownRefresh()
        }
      });
    } else if (that.data.nowtap == 1) {
      wx.request({
        url: app.globalData.url + 'images/get_img_list',
        method: 'POST',
        success: (res) => {
          that.setData({
            imglist: res.data.data
          })
          var dataNumber = res.data.data
          for (var i = 0; i < dataNumber.length; i++) {
            that.setData({
              imgNumber: dataNumber[i][0].length + dataNumber[i][1].length
            })
          }
        },
        complate: function() {
          wx.stopPullDownRefresh()
        }
      });
    } else if (that.data.nowtap == 2) {
      that.setData({
        videoList: that.data.videoList.reverse()
      })
      wx.request({
        url: app.globalData.url + 'medias/get_media_list',
        success: (res) => {
          var data = res.data.data
          that.setData({
            videoList: that.data.videoList.concat(data),
          })
          for (let i = 0; i < that.data.videoList.length; i++) {
            that.setData({
              showList: that.data.showList.concat(true)
            })
          }
        },
        complate: function() {
          that.setData({
            videoList: that.data.videoList.reverse()
          })
          wx.stopPullDownRefresh()
        }
      });
    }
    wx.stopPullDownRefresh()
  },

  /**
   * 切换tap页面
   */
  changeTap: function(e) {
    var that = this
    var tapid = e.currentTarget.dataset.tapid
    this.setData({
      nowtap: tapid
    })
    if (tapid == 0) {
      // 刷新每日一文
      wx.getStorage({
        key: 'todayArticle',
        success: (res) => {
          // console.log(res);
          that.setData({
            article: res.data
          })
        },
        fail:()=>{
          that.getDayArticle()
        }
      });
      wx.setNavigationBarTitle({
        title: '每日一文'
      });
      wx.getStorage({
        key: 'articleStorage',
        success: (res)=>{
          var data = res.data
          console.log(data);
          
          for(let i = 0 ; i < data.length ; i ++){
            if(data[i].title == that.data.article.title){
              that.setData({
                is_art_collect:true
              })
              return
            }
          }
        }
      });
      var back = wx.getBackgroundAudioManager()
      if (that.data.is_play) {
        back.play()
        that.setData({
          is_animation: true,
        })
      }
    } else if (tapid == 1) {
      // 刷新图片
      that.getImgList(1)
      wx.setNavigationBarTitle({
        title: '精选图片'
      });
      var back = wx.getBackgroundAudioManager()
      if (that.data.is_play) {
        back.play()
        that.setData({
          is_animation: true,
        })
      }
    } else if (tapid == 2) {
      wx.getStorage({
        key: 'videoStorage',
        success: (res)=>{
          that.setData({
            vStorage:res.data
          })
        }
      });
      // 刷新视频
      that.getVideoList()
      wx.setNavigationBarTitle({
        title: '视觉盛宴'
      });
      var back = wx.getBackgroundAudioManager()
      if (!that.data.is_play) {
        back.pause()
        that.setData({
          is_animation: false,
        })
      }
    }
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },

  // 获取今日的每日一文
  getDayArticle: function() {
    var that = this
    wx.request({
      url: app.globalData.url + 'articles/today',
      success: (res) => {
        // console.log(res);
        that.setData({
          article: res.data.data
        })
        wx.setStorage({
          key: 'todayArticle',
          data: res.data.data,
          success: (res) => {}
        });
      },
      fail: () => {}
    });
  },
  // 随机每日一文
  randomArticle: function() {
    var that = this
    wx.request({
      url: app.globalData.url + 'articles/random',
      method: 'POST',
      success: (res) => {
        // console.log(res);
        that.setData({
          article: res.data.data,
          is_art_collect:false
        })
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 300
        })
      },
      fail: () => {}
    });
  },

  // 回到今日的每日一文
  backTodayArticle: function() {
    var that = this
    wx.getStorage({
      key: 'todayArticle',
      success: (res) => {
        // console.log(res);
        that.setData({
          article: res.data
        })
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 300
        })
      }
    });
  },

  // 获取图片列表
  getImgList: function() {
    var that = this
    wx.request({
      url: app.globalData.url + 'images/get_img_list',
      data: {},
      method: 'POST',
      success: (res) => {
        // console.log(res.data.data);

        that.setData({
          imglist: that.data.imglist.concat(res.data.data)
        })
        var dataNumber = res.data.data
        for (var i = 0; i < dataNumber.length; i++) {
          that.setData({
            imgNumber: that.data.imgNumber.concat(dataNumber[i][0].length + dataNumber[i][1].length)
          })
        }
      }
    });
  },

  // 预览图片
  previewImage: function(e) {
    var url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: [url]
    })
  },

  // 获取视频列表
  getVideoList: function() {
    var that = this
    wx.request({
      url: app.globalData.url + 'medias/get_media_list/',
      method: 'POST',
      success: (res) => {
        var data = res.data.data
        
        for (let i = 0; i < data.length; i++) {
          // var showitem = that.data.showList[i]
          that.setData({
            showList: that.data.showList.concat(true)
          })
        }
        that.setData({
          videoList: that.data.videoList.concat(data)
        })
      }
    });
  },

  /*
   *点击自定义视频封面开始播放
   */
  playvedio: function(e) {
    var that = this
    // 暂停之前播放的视频
    var preId = 'myvedio' + that.data.preVideoId
    var preIndex = that.data.preVideoIndex
    let preVideo = wx.createVideoContext(preId, this)
    preVideo.pause()
    var preShow = 'showList[' + preIndex + ']'
    this.setData({
      [preShow]: true,
    })

    // 播放当前视频
    var videoId = 'myvedio' + e.currentTarget.dataset.id
    var videoIndex = e.currentTarget.dataset.index
    let vediocon = wx.createVideoContext(videoId, this)
    vediocon.play()
    var nowShow = 'showList[' + videoIndex + ']'
    this.setData({
      [nowShow]: false,
      preVideoId: e.currentTarget.dataset.id
    })
  },

  /*
   *视频播放完毕重新上封面
   */
  endvedio: function(e) {
    var videoId = 'myvedio' + e.currentTarget.dataset.id
    let vediocon = wx.createVideoContext(videoId, this)
    this.setData({
      show: true
    })
  },

  /**
   * 当发生错误时触发error事件，event.detail = {errMsg: 'something wrong'}
   */
  videoErrorCallback: function(e) {
    console.log('视频错误信息:')
    console.log(e.detail.errMsg)
  },

  // 获取音乐
  getMusic: function() {
    var that = this
    wx.request({
      url: app.globalData.url + 'medias/query_music',
      data: {},
      method: 'POST',
      success: (res) => {
        var back = wx.getBackgroundAudioManager()
        that.setData({
          nowMusic: res.data.data,
          first_audio_url: res.data.data.url,
          nowMusicId: res.data.data.id,
          musicIdList: that.data.musicIdList.concat(res.data.data.id)
        })
        // back.src = that.data.nowMusic.url
        back.title = res.data.data.title
        back.coverImgUrl = res.data.data.cover
      },
    });
  },

  audioPlay: function() {
    var that = this
    var back = wx.getBackgroundAudioManager()
    if (!that.data.is_play) {
      if (that.data.is_first_play) {
        back.src = that.data.first_audio_url
      }
      back.play();
      back.onPlay(() => {
        console.log('audioPlay onplay');
      });
      that.setData({
        is_play: true,
        is_animation: true,
        is_first_play: false
      })
    } else {
      back.pause();
      back.onPause(() => {
        console.log('audioPlay onpause');
      });
      that.setData({
        is_play: false,
        is_animation: false
      })
    }
    // 上/下一首
    back.onPrev(() => {
      var that = this
      console.log('上一首');
      var musicIdList = that.data.musicIdList

      var id
      if (musicIdList.length == 10) {
        id = musicIdList[0]
      } else {
        console.log(musicIdList);

        var nowid = that.data.nowMusicId
        musicIdList.find(function(value, index) {
          if (value === nowid) {
            console.log(index);

            console.log(musicIdList[index]);

            //则包含该元素
            that.changeMusic('prev', musicIdList[index])
          }
        })

      }
    })
    back.onNext(() => {
      that.changeMusic('next')
    })

  },

  // 上下切歌
  changeMusic: function() {
    var that = this

    var change = arguments[0]
    var id = arguments[1]

    var back = wx.getBackgroundAudioManager()

    if (change == 'prev') {
      console.log(arguments);

      console.log('id --- ' + id);

      // 上一曲
      wx.request({
        url: app.globalData.url + 'medias/query_music?id=' + id,
        method: 'POST',
        success: (res) => {
          console.log(res);

          // back.stop()
          back.src = res.data.data.url
          back.title = res.data.data.title
          back.coverImgUrl = res.data.data.cover
          // back.play();
          back.onPlay(() => {
            console.log('changeMusic onplay');
          });
          that.setData({
            is_play: true,
            is_animation: true
          })
        }
      });
    } else if (change == 'next') {
      // 下一曲
      wx.request({
        url: app.globalData.url + 'medias/query_music',
        method: 'POST',
        success: (res) => {
          that.setData({
            nowMusic: res.data.data,
            musicIdList: that.data.musicIdList.concat(res.data.data.id),
          })
          // back.stop()
          back.src = that.data.nowMusic.url
          back.title = that.data.nowMusic.title
          back.coverImgUrl = that.data.nowMusic.cover
          // back.play();
          back.onPlay(() => {
            console.log('changeMusic onplay');
          });
          that.setData({
            is_play: true,
            is_animation: true
          })
        }
      });
    }

  },

  /**
   * 添加收藏
   */
  addCollect: function(e) {
    var that = this
    var type = e.currentTarget.dataset.type

    if (type == 'video') {
      var videoStorage = wx.getStorageSync('videoStorage') ? wx.getStorageSync('videoStorage') : []
      var video = {
        id: e.currentTarget.dataset.id,
        title: e.currentTarget.dataset.title,
        cover: e.currentTarget.dataset.cover,
        desc: e.currentTarget.dataset.desc,
      }
      videoStorage.unshift(video)
      wx.setStorageSync('videoStorage', videoStorage)      
      
      wx.showToast({
        title: '收藏成功,请至收藏页面查看',
        icon: 'none',
        duration: 2000,
        mask: false,
        success: (result) => {}
      });
      
    } else if (type == 'article') {
      var articleStorage = wx.getStorageSync('articleStorage') ? wx.getStorageSync('articleStorage') : []
      var article = {
        id: e.currentTarget.dataset.id,
        title: e.currentTarget.dataset.title,
        cover: '/images/collectAltCover.png',
      }
      that.setData({
        is_art_collect:!that.data.is_art_collect
      })
      if(that.data.is_art_collect){
        articleStorage.unshift(article)
        wx.setStorageSync('articleStorage', articleStorage)
        wx.showToast({
          title: '收藏成功',
          icon: 'none',
          duration: 1000,
          mask: false,
          success: (result) => {}
        });
      }else{
        for(let i = 0 ; i < articleStorage.length ; i ++){
          if(articleStorage[i].title == that.data.article.title){
            articleStorage.splice(i , 1);
          }
        }
        wx.setStorageSync('articleStorage', articleStorage)
        wx.showToast({
          title: '取消收藏',
          icon: 'none',
          duration: 1000,
          mask: false,
          success: (result) => {}
        });
      }
    }
  },


  /**
   * form模板消息
   */
  formSubmit:function(){

  },
  // 上传form_id
  uploadFormid :function(formid){
    var that = this
    //通过网络请求发送openid和formIds到服务器
    wx.request({
      url: app.globalData.url + 'accs/handler_formid',
      method: 'POST',
      data: {
        ghid: 'gh_91d384b2777f',
        openid: app.globalData.openId,
        formid: formid
      },
      success: function (res) {
        if(res.data.msg == 'ok'){
          app.globalData.isFirstOpen = false
        }
      }
    });
  }
})